#include "zDlgExcute.h"
#include "ui_zDlgExcute.h"

#include <QDateTime>
#include <QTime>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QFileInfo>


zDlgExcute::zDlgExcute(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::zDlgExcute)
{
    ui->setupUi(this);
    setLayout(ui->m_pMainLayout);
    m_listGet = QStringList();

    ui->m_pLineEdit->setFont(QFont("黑体", 40));

    m_pMove = new QMovie ("./long.gif");

    m_pLabel = new QLabel(this);
    m_pLabel->setMovie(m_pMove);
    m_pLabel->setAlignment(Qt::AlignCenter);

    m_player = new QMediaPlayer();
}

zDlgExcute::~zDlgExcute()
{
    SetFileInfo(m_strFilePath, m_listName);
    QFileInfo info(m_strFilePath);
    QString strNew = info.absolutePath() + "//" + QDateTime::currentDateTime().toString("MM-dd-hh-mm-ss") + ".txt";
    SetFileInfo(strNew, m_listGet);
    delete ui;
}

void zDlgExcute::SetFilePath(const QString &strFilePath)
{
    m_strFilePath = strFilePath;

    qDebug()<< m_strFilePath;

    QFile file(m_strFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
         return;

    QTextStream in(&file);
    while (!in.atEnd())
    {
        QString line = in.readLine();
        m_listName<<line;
    }

    qDebug()<< m_listName;
}

void zDlgExcute::SetFileInfo(const QString &strFileName, const QStringList &listInfo)
{
    QFile file(strFileName);
    if (!file.open( QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
    {
        qDebug()<<"Set File Info Failed";
        return;
    }

    QTextStream in(&file);
    for(int i = 0; i < listInfo.size(); ++i)
    {
        in << listInfo[i] <<"\n";
    }
    file.close();
    return;
}

void zDlgExcute::on_m_pBtnNext_clicked()
{
    if(m_listName.size() >= 1)
    {
         ui->m_pLineEdit->clear();
        m_pLabel->setGeometry(ui->m_pLineEdit->x(), ui->m_pLineEdit->y(),
                      ui->m_pLineEdit->width(), ui->m_pLineEdit->height());
        m_pLabel->show();
        m_pLabel->raise();
        m_pMove->start();

        QTime time;
        time.start();
        while(time.elapsed() < 1000)
            QCoreApplication::processEvents();

        m_pLabel->hide();

        time= QTime::currentTime();
        qsrand(time.msec()+time.second()*1000);
        int nIndex = qrand() % m_listName.size();
        qDebug()<<nIndex;

        m_listGet.push_back(m_listName[nIndex]);
        ui->m_pLineEdit->setText(m_listName[nIndex]);
        m_listName.removeAt(nIndex);
    }
    else
    {
        ui->m_pLineEdit->setText("OVER");
    }
}

void zDlgExcute::resizeEvent(QResizeEvent *event)
{
    this->QWidget::resizeEvent(event);

    ui->m_pLineEdit->setFont(QFont("微软雅黑", this->height()/4));
}
